package com.example.fanpaiyouxi

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class CardGameActivity : AppCompatActivity() {

    private lateinit var gridContainer: LinearLayout
    private lateinit var tvScore: TextView
    private lateinit var tvMoves: TextView
    private lateinit var btnRestart: Button
    private lateinit var btnBack: Button

    private lateinit var gameModel: CardGameModel
    private var score = 0
    private var moves = 0
    private var highScore = 0

    private val handler = Handler(Looper.getMainLooper())
    private val cardViews = mutableListOf<ImageView>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_card_game)

        highScore = intent.getIntExtra("high_score", 0)

        initViews()
        setupClickListeners()
        startNewGame()
    }

    private fun initViews() {
        gridContainer = findViewById(R.id.gridContainer)
        tvScore = findViewById(R.id.tvScore)
        tvMoves = findViewById(R.id.tvMoves)
        btnRestart = findViewById(R.id.btnRestart)
        btnBack = findViewById(R.id.btnBack)
    }

    private fun setupClickListeners() {
        btnRestart.setOnClickListener {
            startNewGame()
        }

        btnBack.setOnClickListener {
            finish()
        }
    }

    private fun startNewGame() {
        score = 0
        moves = 0
        gameModel = CardGameModel()
        updateUI()
        createCardViews()
    }

    private fun createCardViews() {
        gridContainer.removeAllViews()
        cardViews.clear()

        // 计算每张牌的尺寸
        val screenWidth = resources.displayMetrics.widthPixels
        val padding = 16 * 2 // 左右padding
        val margin = 8 * 8   // margin总和
        val availableWidth = screenWidth - padding - margin
        val cardSize = availableWidth / 4

        // 创建4行
        for (row in 0 until 4) {
            val rowLayout = LinearLayout(this).apply {
                layoutParams = LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    0,
                    1.0f
                )
                orientation = LinearLayout.HORIZONTAL
                weightSum = 4f
            }

            // 每行创建4列
            for (col in 0 until 4) {
                val position = row * 4 + col
                val cardView = ImageView(this).apply {
                    layoutParams = LinearLayout.LayoutParams(
                        0,
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        1.0f
                    ).apply {
                        setMargins(4, 4, 4, 4)
                    }
                    scaleType = ImageView.ScaleType.CENTER_CROP
                    setOnClickListener {
                        onCardClick(position)
                    }
                }
                updateCardView(position, cardView)
                rowLayout.addView(cardView)
                cardViews.add(cardView)
            }
            gridContainer.addView(rowLayout)
        }
    }

    private fun onCardClick(position: Int) {
        if (gameModel.isCardMatched(position)) return

        val result = gameModel.flipCard(position)

        when (result) {
            is CardGameModel.FlipResult.Match -> {
                moves++
                score += 10
                updateCardViews()
                updateUI()
                if (gameModel.isGameComplete()) {
                    handler.postDelayed({
                        showGameComplete()
                    }, 500)
                }
            }
            is CardGameModel.FlipResult.Mismatch -> {
                moves++
                updateCardViews()
                updateUI()
                handler.postDelayed({
                    gameModel.resetFlippedCards()
                    updateCardViews()
                }, 1000)
            }
            is CardGameModel.FlipResult.FirstCard -> {
                moves++
                updateCardViews()
                updateUI()
            }
            is CardGameModel.FlipResult.NoChange -> {
                // 不做任何操作
            }
        }
    }

    private fun updateCardViews() {
        for (i in gameModel.cards.indices) {
            updateCardView(i, cardViews[i])
        }
    }

    private fun updateCardView(position: Int, cardView: ImageView) {
        val card = gameModel.cards[position]

        when {
            card.isMatched -> {
                // 匹配的牌显示为暗色
                val resourceId = getCardImageResource(card.value)
                cardView.setImageResource(resourceId)
                cardView.alpha = 0.5f
                cardView.isEnabled = false
            }
            card.isFaceUp -> {
                // 翻开的牌显示正常颜色
                val resourceId = getCardImageResource(card.value)
                cardView.setImageResource(resourceId)
                cardView.alpha = 1.0f
                cardView.isEnabled = true
            }
            else -> {
                // 未翻开的牌显示牌背
                cardView.setImageResource(R.drawable.card_back)
                cardView.alpha = 1.0f
                cardView.isEnabled = true
            }
        }
    }

    private fun getCardImageResource(cardValue: Int): Int {
        return when (cardValue) {
            1 -> R.drawable.card_1
            2 -> R.drawable.card_2
            3 -> R.drawable.card_3
            4 -> R.drawable.card_4
            5 -> R.drawable.card_5
            6 -> R.drawable.card_6
            7 -> R.drawable.card_7
            8 -> R.drawable.card_8
            else -> R.drawable.card_back
        }
    }

    private fun updateUI() {
        tvScore.text = getString(R.string.score, score)
        tvMoves.text = getString(R.string.moves, moves)
    }

    private fun showGameComplete() {
        val finalScore = score
        if (finalScore > highScore) {
            highScore = finalScore
            val resultIntent = Intent().apply {
                putExtra("high_score", highScore)
            }
            setResult(RESULT_OK, resultIntent)
        }

        Toast.makeText(this, getString(R.string.game_over, finalScore), Toast.LENGTH_LONG).show()
    }
}